package com.haohan.cloud.scm.common.tools.thread;

import org.springframework.core.task.TaskDecorator;
import org.springframework.lang.NonNull;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author dy
 * @date 2020/3/13
 * 安全 上下文 复制
 */
public class ContextCopyingDecorator implements TaskDecorator {

    @NonNull
    @Override
    public Runnable decorate(@NonNull Runnable runnable) {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return () -> {
            try {
                SecurityContextHolder.setContext(securityContext);
                runnable.run();
            } finally {
                SecurityContextHolder.clearContext();
            }
        };
    }
}
